package com.turbo.boot.crawler.spider.worker.impl.quota;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.turbo.boot.crawler.spider.worker.BaseTurboApiCrawler;
import com.turbo.utils.net.HttpHelper;
import com.xuxueli.crawler.rundata.RunData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述
 *
 * @author wuyn
 * @since 2024/5/28
 */
@Slf4j
@Service("braemarScreenExchangeCrawler")
public class BraemarScreenExchangeCrawler extends BaseTurboApiCrawler<BraemarScreenExchangeCrawlerPageParser.PageVo> {

    private static final HttpHelper httpHelper = new HttpHelper();


//    public boolean build() {
//        xxlCrawlerBuilder.setUrls("https://api.braemarscreen.com/api/graphql");
//        return true;
//    }

    @Override
    public String remoteCall(RunData runData) {

        String target = runData.getUrl();
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");
            String body = "{\"operationName\":\"homepageMarkets\",\"variables\":{},\"query\":\"query homepageMarkets {\\n  brokerSite {\\n    ticker {\\n      name\\n      products {\\n        id\\n        name\\n        price\\n        prevClose\\n        __typename\\n      }\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\"}";
            return httpHelper.post(target, body, headers);
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    @Override
    public void parse(String result) {
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<BraemarScreenExchangeCrawlerPageParser.PageVo> pageVos = JSON.parseArray(jsonObject.getJSONObject("data").getJSONObject("brokerSite").getString("ticker"), BraemarScreenExchangeCrawlerPageParser.PageVo.class);
        for (BraemarScreenExchangeCrawlerPageParser.PageVo pageVo : pageVos) {
            try {
                getPageParser().parse(pageVo);
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }


//    @Override
//    protected BaseTurboCrawlerPageParser<BraemarScreenExchangeCrawlerPageParser.PageVo> getPageParser() {
//        return new BraemarScreenExchangeCrawlerPageParser();
//    }


    public static void main(String[] args) {
        BraemarScreenExchangeCrawler braemarScreenExchangeCrawler = new BraemarScreenExchangeCrawler();
        braemarScreenExchangeCrawler.crawl();
    }

}